package dmf.generator.ecore2d.popup.actions;


import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.xpand2.XpandExecutionContextImpl;
import org.eclipse.xpand2.XpandFacade;
import org.eclipse.xpand2.output.Outlet;
import org.eclipse.xpand2.output.OutputImpl;
import org.eclipse.xtend.typesystem.emf.EmfRegistryMetaModel;

public class Generator {
	
	static public void generateNative(IPath sourceFile, IPath container)
	{
       // WrapPackage.eINSTANCE.eClass();
		
		Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
		Map<String, Object> m = reg.getExtensionToFactoryMap();
		m.put("ecore", new XMIResourceFactoryImpl());
		

		// Obtain a new resource set
		ResourceSet resSet = new ResourceSetImpl();
		
		Resource resource = resSet.getResource(URI.createFileURI(sourceFile.toString()), true);
		EPackage project = (EPackage)resource.getContents().get(0);
		
		OutputImpl output = new OutputImpl();
	    Outlet outlet = new Outlet(container.toPortableString());
	    outlet.setOverwrite(true);
	    output.addOutlet(outlet);

	    // create execution context
	    Map globalVarsMap = new HashMap();
	    XpandExecutionContextImpl execCtx = new XpandExecutionContextImpl(output, null, globalVarsMap, null, null);
	    EmfRegistryMetaModel metamodel = new EmfRegistryMetaModel() {
	        @Override
	        protected EPackage[] allPackages() {
	            return new EPackage[] {EcorePackage.eINSTANCE};
	        }
	    };
	    execCtx.registerMetaModel(metamodel);

	    // generate
	    XpandFacade facade = XpandFacade.create(execCtx);
	    String templatePath = "template::GenerateEMF4D::main";
	    facade.evaluate(templatePath, project);

	    // refresh the project to get external updates:
	    //resource.ref//refreshLocal(IResource.DEPTH_INFINITE, this.get);
		try {
			ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
